package cn.mumzone.pos.api;


import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.BuildConfig;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Author Chaney
 * Date   2017/3/6 下午9:45.
 * EMail  qiuzhenhuan.hi@gmail.com
 */


public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {

        Request request = chain.request();
        RequestBody requestBody = request.body();
        if (request.method().equals("GET")) {
            String sUrl = request.url().toString();

            int index = sUrl.indexOf("?");
            if (index > 0) {
                sUrl = sUrl + "&";
            } else {
                sUrl = sUrl + "?";
            }
            sUrl = sUrl + String.format("token=%s&shopId=%s&companyId=%s&sellerId=%s&v=%s&source=1",
                    AppConstants.TEMP_TOKEN, AppConstants.TEMP_SHOP_ID, AppConstants.TEMP_COMPANY_ID,
                    AppConstants.TEMP_SELLER_ID, BuildConfig.VERSION_CODE);

            request = request.newBuilder().url(sUrl).build();   //重新构建
        } else if (request.method().equals("POST")) {
            if (requestBody instanceof FormBody) {
                FormBody.Builder builder = new FormBody.Builder();
                FormBody formBody = (FormBody) requestBody;
                for (int i = 0; i < formBody.size(); i++) {    // 如果要对已有的参数做进一步处理可以这样拿到参数
                    builder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                }
                builder.addEncoded("token", AppConstants.TEMP_TOKEN);  //添加公共参数
                builder.addEncoded("shopId", AppConstants.TEMP_SHOP_ID);
                builder.addEncoded("companyId", AppConstants.TEMP_COMPANY_ID);
                builder.addEncoded("sellerId", AppConstants.TEMP_SELLER_ID);
                builder.addEncoded("v", String.valueOf(BuildConfig.VERSION_CODE));
                builder.addEncoded("source", "1"); // 0 App 1pos
                request = request.newBuilder().post(builder.build()).build();  //重新构建
                return chain.proceed(request);
            }

            MediaType mediaType = request.body().contentType();
            if (mediaType != null && "json".equals(mediaType.subtype())) {
                String postJson = bodyToString(request.body());
                if (!TextUtils.isEmpty(postJson)) {
                    try {
                        JSON.parseArray(postJson);
                    } catch (Exception e) {
                        JSONObject jsonObject = JSONObject.parseObject(postJson);
                        jsonObject.put("token", AppConstants.TEMP_TOKEN);
                        jsonObject.put("shopId", AppConstants.TEMP_SHOP_ID);
                        jsonObject.put("companyId", AppConstants.TEMP_COMPANY_ID);
                        jsonObject.put("sellerId", AppConstants.TEMP_SELLER_ID);
                        jsonObject.put("source", "1");
                        jsonObject.put("v", String.valueOf(BuildConfig.VERSION_CODE));
                        RequestBody newBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                                jsonObject.toJSONString());
                        request = request.newBuilder().post(newBody).build();
                    }
                }
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", AppConstants.TEMP_TOKEN);
                jsonObject.put("shopId", AppConstants.TEMP_SHOP_ID);
                jsonObject.put("companyId", AppConstants.TEMP_COMPANY_ID);
                jsonObject.put("sellerId", AppConstants.TEMP_SELLER_ID);
                jsonObject.put("source", "1");
                jsonObject.put("v", String.valueOf(BuildConfig.VERSION_CODE));
                RequestBody newBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                        jsonObject.toJSONString());
                request = request.newBuilder().post(newBody).build();
            }
        }
        return chain.proceed(request);
    }

    private String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "";
        }
    }


}
